<?php
declare (strict_types=1);

namespace app\home\middleware;


use app\common\model\HomeTokenModel;
use app\common\model\UserModel;
use think\exception\HttpException;

class Auth
{
    public function handle($request, \Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');

        $path_info = config('ToConfig.app_system.app_system') ? $_SERVER['REQUEST_URI']:$_SERVER['PATH_INFO'];
        if (strstr($path_info,'/login')){
            return $next($request);
        }
        //校验token
        $token = $request->header('x-csrf-token');
        if (!$token) $token = isset($_SERVER['X-CSRF-TOKEN']) ?$_SERVER['X-CSRF-TOKEN']:'';
        if (empty($token)) return show([], config('ToConfig.http_code.error'), 'token不存在');;
        //查询token
        $res = (new HomeTokenModel())->where('token', $token)->find();
        if (empty($res)) return show([], config('ToConfig.http_code.error'), 'token无效');;

        //校验是否过期的token
        $expiration_time = time() - strtotime($res['create_time']);
        if ($expiration_time >= env('token.home_token_time', 10)) return show([], config('ToConfig.http_code.error'), 'token过期');

        //校验成功处理逻辑
        //查询用户数据并存入session
        $res = (new UserModel())->find($res['user_id']);
        if (empty($res)) return show([], config('ToConfig.http_code.error'), '用户不存在');;
        if ($res->status != 1) throw new HttpException(404, '网络错误');
        //session 登陆写入日志
        //if(empty(session())) (new \app\common\service\LoginLog())->login();
        $res = $res->toArray();
        $res['token'] = $token;
        session('home_user', $res);
        // 添加中间件执行代码
        return $next($request);

    }

}
